<template>
  <div class="salesman-table-container">
    <!-- 登录入口链接 -->
    <div class="login-link">
      业务员登录入口：<a href="https://support.bambocat.com/salesman.php?store_id=1" target="_blank">https://support.bambocat.com/salesman.php?store_id=1</a>
    </div>

    <!-- 操作栏：添加业务员、搜索输入框 + 搜索按钮 -->
    <el-row :gutter="20" class="operation-bar">
      <el-col :span="2">
        <el-button type="primary" @click="handleAddSalesman">添加业务员</el-button>
      </el-col>
      <!-- 调整：输入框和按钮放在同一列，横向排列 -->
      <el-col :span="6" :offset="16">
        <div class="search-wrapper">
          <el-input
            v-model="searchQuery"
            placeholder="请输入要查询的联系人"
            prefix-icon="el-icon-search"
            @keyup.enter="handleSearch"
            style="width: 75%; margin-right: 10px;"
          />
          <el-button 
            type="primary" 
            @click="handleSearch"
            style="width: 20%;"
          >
            搜索
          </el-button>
        </div>
      </el-col>
    </el-row>

    <!-- 业务员账户列表 -->
    <el-table
      :data="salesmanList"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
    >
      <el-table-column prop="businessmanId" label="ID" width="50" />
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="name" label="联系人" />
      <el-table-column prop="createTime" label="创建日期">
        <template #default="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-switch v-model="scope.row.status" @click="zk(scope.row)" :active-value="1" :inactive-value="0" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="text" @click="handleBelongDevice(scope.row)">负责设备</el-button>
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pageNo"
      :page-sizes="[2,5, 10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      style="margin-top: 20px; text-align: right"
    />

    <!-- 添加业务员模态框 -->
    <el-dialog
      title="添加业务员"
      v-model="addDialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <!-- 关键：添加formRef用于触发表单验证 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        label-width="120px"
        :rules="formRules"
        class="add-form"
      >
        <el-form-item label="业务员姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入业务员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="addForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="负责区域" prop="responsibleArea">
          <el-input v-model="addForm.responsibleArea" placeholder="请输入负责省份，如：湖南省" />
        </el-form-item>
        <el-form-item label="初始密码" prop="password">
          <el-input 
            v-model="addForm.password" 
            placeholder="请设置初始密码" 
            type="password"
            show-password
          />
        </el-form-item>
        <el-form-item label="关联操作员" prop="operatorId">
          <el-select v-model="addForm.operatorId" placeholder="请选择关联操作员">
            <el-option 
              v-for="operator in operators" 
              :key="operator.operatorId" 
              :label="operator.name" 
              :value="operator.operatorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="addForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="submitAddForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑业务员模态框 -->
    <el-dialog
      title="编辑业务员"
      v-model="editDialogVisible"
      width="600px"
      :before-close="handleEditClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        label-width="120px"
        :rules="formRules"
        class="add-form"
      >
        <el-form-item v-show="false" prop="businessmanId">
          <el-input v-model="editForm.businessmanId" />
        </el-form-item>
        <el-form-item label="业务员姓名" prop="name">
          <el-input v-model="editForm.name" :disabled="true" placeholder="请输入业务员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="editForm.department" placeholder="请输入所属部门" />
        </el-form-item>
        <el-form-item label="负责区域" prop="responsibleArea">
          <el-input v-model="editForm.responsibleArea" placeholder="请输入负责省份，如：湖南省" />
        </el-form-item>
        <el-form-item label="关联操作员" prop="operatorId">
          <el-select v-model="editForm.operatorId" placeholder="请选择关联操作员">
            <el-option 
              v-for="operator in operators" 
              :key="operator.operatorId" 
              :label="operator.name" 
              :value="operator.operatorId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="editForm.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleEditClose">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 归属设备列表模态框 -->
    <el-dialog
      title="业务员负责设备列表"
      v-model="deviceDialogVisible"
      width="900px"
      :before-close="handleDeviceDialogClose"
      destroy-on-close
    >
      <el-table
        :data="deviceList"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :empty-text="isLoadingDevice ? '加载中...' : '该业务员暂无负责设备'"
      >
        <el-table-column prop="equipmentId" label="设备ID" width="80" align="center" />
        <el-table-column prop="brand" label="设备品牌" min-width="180" />
        <el-table-column prop="model" label="设备型号" min-width="150" />
        <el-table-column prop="year" label="设备年份" min-width="150" />
        <el-table-column prop="price" label="设备价格" min-width="150" />
        <el-table-column prop="contactName" label="设备联系人" min-width="150" />
        <el-table-column prop="contactPhone" label="设备联系电话" min-width="150" />
        <el-table-column prop="releaseTime" label="发布时间" min-width="180">
          <template #default="scope">
            {{ formatDate(scope.row.releaseTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="设备状态" width="120">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
              {{ scope.row.status === 0 ? '未审核':scope.row.status === 1 ? '已上架':scope.row.status === 2 ? '已下架':scope.row.status === 3 ? '已成交':'设备状态异常'}}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="设备所在地（省/ 市 / 区）" min-width="200" />
      </el-table>
      <template #footer>
        <el-button @click="handleDeviceDialogClose">关闭</el-button>
      </template>
    </el-dialog>
  
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from 'vue';
import httpInstance from '../../utils/http';
import { ElMessage, ElMessageBox } from 'element-plus';

// 业务员列表数据
const salesmanList = ref([]);
// 搜索条件
const searchQuery = ref('');
// 分页参数
const pageNo = ref(1);
const pageSize = ref(5);
const total = ref(0);
// 添加模态框相关
const addDialogVisible = ref(false);
const addFormRef = ref(null); // 关键：添加表单的ref引用，用于触发表单验证
// 操作员列表
const operators = ref([]);

// 添加表单数据
const addForm = reactive({
  name: '',          // 业务员姓名
  phone: '',         // 手机号
  department: '',    // 所属部门
  responsibleArea: '', // 负责区域
  password: '',      // 初始密码
  operatorId: '',    // 关联操作员ID
  status: 1          // 状态，默认启用(1)
});

// 编辑模态框相关
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = reactive({
  businessmanId: '',
  name: '',
  phone: '',
  department: '',
  responsibleArea: '',
  operatorId: '',
  status: 1
});

// 归属设备相关
const deviceDialogVisible = ref(false);
const deviceList = ref([]);
const currentSalesmanId = ref('');
const isLoadingDevice = ref(false); // 补充设备加载状态，优化空文本显示


// 关键：完善表单验证规则，所有必填项强制校验
const formRules = reactive({
  name: [
    { required: true, message: '请输入业务员姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '姓名长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入所属部门', trigger: 'blur' } // 文本框用blur触发，失焦即校验
  ],
  responsibleArea: [
    { required: true, message: '请输入负责区域', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请设置初始密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于 6 个字符', trigger: 'blur' }
  ],
  operatorId: [
    { required: true, message: '请选择关联操作员', trigger: 'change' } // 下拉框用change触发
  ]
});

// 页面加载初始化
onMounted(() => {
  getsalesmanList();
  getOperators();
});

// 获取业务员列表
const getsalesmanList = async () => { 
  try {
    const res = await httpInstance.post(`/eduservice/businessman/getBusinessmanPage/${pageNo.value}/${pageSize.value}`, {
      name: searchQuery.value
    });
    salesmanList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    ElMessage.error('获取业务员列表失败');
  }
};

// 获取操作员列表
const getOperators = async () => {
  try {
    const { data: res } = await httpInstance.post('/eduservice/operator/getOperatorAll');
    operators.value = res.data.list;
  } catch (error) {
    console.error('获取操作员列表失败:', error);
    ElMessage.error('获取操作员列表失败');
  }
};

// 打开添加模态框（重置表单）
const handleAddSalesman = () => {
  // 重置表单数据和验证状态
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
  addForm.status = 1; // 默认启用
  addDialogVisible.value = true;
};

// 关闭添加模态框
const handleClose = () => {
  addDialogVisible.value = false;
  if (addFormRef.value) {
    addFormRef.value.resetFields();
  }
};

// 关闭编辑模态框
const handleEditClose = () => {
  editDialogVisible.value = false;
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
};

// 关键：提交添加表单（带完整验证）
const submitAddForm = async () => {
  try {
    // 1. 触发表单验证：所有必填项未填会自动提示
    await addFormRef.value.validate();

    // 2. 验证操作员是否已存在（原有逻辑保留）
    const { data: vul } = await httpInstance.get(`/eduservice/businessman/getOperatorId/${addForm.operatorId}`);
    if (vul.data.OperatorId != null) {
      ElMessage.warning('该操作员已存在，请换一个操作员选择');
      return;
    }

    // 3. 调用添加接口
    const res = await httpInstance.post(`/eduservice/businessman`, addForm);
    if (res.data.success) {
      ElMessage.success('添加业务员成功');
      addDialogVisible.value = false;
      getsalesmanList(); // 刷新列表
      addFormRef.value.resetFields(); // 重置表单
    } else {
      ElMessage.error(res.message || '添加失败');
    }

  } catch (error) {
    // 表单验证失败会自动触发规则提示，无需额外处理
    if (error.name === 'Error') {
      ElMessage.error('添加业务员失败，请重试');
    }
    console.error('添加失败:', error);
  }
};

// 提交编辑表单
const submitEditForm = async () => {
  try {
    await editFormRef.value.validate();
    const { data: vul } = await httpInstance.get(`/eduservice/businessman/getOperatorId/${editForm.operatorId}`);
    if (vul.data.OperatorId != null) {
      ElMessage.warning('该操作员已存在，请换一个操作员选择');
      return;
    }
    const res = await httpInstance.put(`/eduservice/businessman/`, editForm);
    if (res.data.success) {
      ElMessage.success('编辑业务员成功');
      editDialogVisible.value = false;
      getsalesmanList();
    } else {
      ElMessage.error(res.message || '编辑失败');
    }
  } catch (error) {
    if (error.name === 'Error') {
      ElMessage.error('编辑业务员失败，请重试');
    }
    console.error('编辑失败:', error);
  }
};

// 归属设备相关函数
const getSalesmanDeviceList = async () => {
  try {
    const { data: res } = await httpInstance.post(`eduservice/businessman/getBusinessmanEquipmentByBusinessmanId/${currentSalesmanId.value}`);
    deviceList.value = res.data.list || [];
  } catch (error) {
    console.error('获取设备列表失败：', error);
    ElMessage.error('获取设备信息失败，请重试');
    deviceList.value = [];
  } finally {
  }
};

// 2. 打开设备模态框（修改原handleBelongDevice函数）
const handleBelongDevice = (row) => {
  currentSalesmanId.value = row.businessmanId; // 记录当前业务员ID
  deviceDialogVisible.value = true; // 打开模态框
  getSalesmanDeviceList(); // 立即请求该业务员的设备数据
};

// 3. 关闭设备模态框（重置数据，避免残留）
const handleDeviceDialogClose = () => {
  deviceDialogVisible.value = false;
  currentSalesmanId.value = '';
  deviceList.value = [];
};



//=============================================================


// 处理搜索
const handleSearch = () => {
  pageNo.value = 1; // 重置页码
  getsalesmanList();
};

// 新增：切换每页条数（pageSize 变化时触发）
const handleSizeChange = (val) => {
  pageSize.value = val; // 更新每页条数
  pageNo.value = 1; // 重置为第一页，避免数据漏查
  getsalesmanList(); // 重新请求列表数据
};

// 新增：切换页码（currentPage 变化时触发）
const handleCurrentChange = (val) => {
  pageNo.value = val; // 更新当前页码
  getsalesmanList(); // 重新请求列表数据
};

const handleEdit = (row) => {
  // 1. 深拷贝当前行数据到编辑表单（避免直接修改表格原始数据）
  Object.assign(editForm, JSON.parse(JSON.stringify(row)));
  // 2. 打开编辑弹窗
  editDialogVisible.value = true;
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该业务员吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await httpInstance.delete(`/eduservice/businessman/${row.businessmanId}`);
      ElMessage.success('删除成功');
      getsalesmanList();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 处理修改密码
const handleChangePassword = (row) => {
  console.log('修改密码：', row);
  // 实现修改密码逻辑
};

 const zk = async (row)=>{ 
   const res = await httpInstance.put(`/eduservice/businessman/`, row);
};

// 修改后：替换T为空格，保留年月日和时分秒
const formatDate = (dateStr) => {
  // 若日期为空或非字符串，返回空值避免报错
  if (!dateStr || typeof dateStr !== 'string') return '';
  // 将日期中的"T"替换为空格，保留完整的年月日和时分秒
  return dateStr.replace('T', ' ');
};
</script>

<style scoped>
.salesman-table-container {
  padding: 20px;
}

.login-link {
  margin-bottom: 20px;
  color: #666;
}

.login-link a {
  color: #1890ff;
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}

.operation-bar {
  margin-bottom: 20px;
}

.add-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 15px;
}

/* 归属设备模态框：表格单元格 padding 优化 */
.el-dialog .el-table td,
.el-dialog .el-table th {
  padding: 12px 8px;
}

/* 设备状态标签：微调间距 */
.el-dialog .el-tag {
  padding: 4px 8px;
  font-size: 12px;
}
</style>
